import { PlusOutlined } from "@ant-design/icons";
import { Image, Upload } from "antd";
import React, { useEffect, useState } from "react";
import alert from "../utils/alert";
import client from '../utils/client';
import { isImage } from "../utils/ext";
import DisabledContext from "./disabledContext";
import Iframe from "./Iframe";
import PDFViewer from "./PdfViewer";
import styles from "./uploadField.module.css";
import useModal from "./useModal";

// 导出默认的组件函数 UploadField
export default function UploadField({
  host = '', // 文件上传的服务器地址，不指定则默认为页面所在的服务器地址
  limit = 1 * 1024 * 1024, // 文件大小限制，默认为 1MB
  dir, // 上传目录，不指定会使用默认位置
  value, // 当前文件的值，默认为空
  type, // 文件MIME类型，默认为所有类型
  onChange, // 文件变化时的回调函数
  disabled, // 文件是否禁用，默认为 false
  ...props // 其他属性
}) {
  // 使用 DisabledContext 的 disabled 属性
  const context_disabled = React.useContext(DisabledContext);
  disabled = disabled || context_disabled;

  const [modal, modalHolder] = useModal();
  const [fileList, setFileList] = useState([]);
  const [previewImage, setPreviewImage] = useState();

  useEffect(() => {
    setFileList(!value ? [] : [{
      uid: -1,
      name: value,
      status: 'done',
      type: type || (isImage(value.split('.').pop()) ? 'image/*' : 'application/*'),
      url: value.startsWith("http") ? value : `${host}/api/doc?access_token=${client.get('TOKEN')}&file=${encodeURIComponent(value)}`,
    }]);
  }, [host, value, type]);

  async function onPreview(file) {
    if (!file.url) return null;
    const ext = file.name.split('.').pop();
    if (isImage(ext) || (type && type.startsWith('image/'))) {
      return setPreviewImage(file.url);
    } else {
      if (ext.toUpperCase() === 'PDF') {
        const mobile = <PDFViewer url={file.url} />;
        const pc = <Iframe title={file.name} src={file.url} />;
        modal.open({
          width: '90%',
          bodyStyle: { height: 'calc(100vh - 60px)' },
          content: navigator.userAgent.includes('Mobile') ? mobile : pc,
          footer: null,
        });
      } else {
        client.doc.download(file.name);
      }
    }
  }

  return (
    <>
      <Upload
        listType="picture-card"
        action={host + "/api/doc"}
        name="files"
        disabled={disabled}
        className={styles.upload}
        headers={{ 'Authorization': 'Bearer ' + client.get('TOKEN') }}
        data={dir ? { dir } : null}
        beforeUpload={(file) => {
          if (file.size > limit) {
            alert("文件大小超出" + (limit / 1024 / 1024).toFixed(2) + "MB限制");
            return false;
          }
          return !disabled;
        }}
        onChange={info => {
          setFileList(info.fileList);
          if (info.file.status === 'done') {
            const [path] = info.file.response;
            onChange(path);
          }
        }}
        fileList={fileList} onRemove={() => onChange()} onPreview={onPreview} {...props}>
        {fileList.length > 0 ? null : <PlusOutlined />}
      </Upload>
      <Image style={{ display: 'none' }}
        preview={{
          visible: !!previewImage,
          src: previewImage,
          onVisibleChange: (value) => {
            setPreviewImage(null);
          },
        }}
      />
      {modalHolder}
    </>
  );
}